package com.fuhaiwei.domain.service.impl;

import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import com.fuhaiwei.basic.spring.BeanFactory;
import com.fuhaiwei.basic.utils.Logger;
import com.fuhaiwei.domain.dao.UserDao;
import com.fuhaiwei.domain.model.User;
import com.fuhaiwei.domain.service.LoginService;
import com.fuhaiwei.domain.service.LoginResult;
import com.fuhaiwei.domain.service.ModifyService;
import com.fuhaiwei.domain.service.ModifyResult;

public class ModifyServiceImpl implements ModifyService {

	private UserDao userDao;
	private LoginService loginService;

	public ModifyResult doModify(String username, String oldpassword,
			String newpassword) {
		LoginResult doLogin = loginService.doLogin(username, oldpassword);
		if (doLogin == LoginResult.LOGIN_SUCCESS) {
			if (doDBModify(username, newpassword) == false) {
				return ModifyResult.DATABASE_ERROR;
			}
			if (loginService.doLogin(username, newpassword) == LoginResult.LOGIN_SUCCESS) {
				return ModifyResult.MODIFY_SUCCESS;
			} else {
				Logger logger = (Logger) BeanFactory.getBean("logger");
				logger.warn("doDBModify return true, but doLogin() failure");
				return ModifyResult.DATABASE_ERROR;
			}
		}
		if (doLogin == LoginResult.PASSWORD_WORNG) {
			return ModifyResult.PASSWORD_WORNG;
		}
		if (doLogin == LoginResult.USERNAME_NOTEXISTS) {
			return ModifyResult.USERNAME_NOTEXISTS;
		}
		if (doLogin == LoginResult.DATABASE_ERROR) {
			return ModifyResult.DATABASE_ERROR;
		}
		return null;
	}

	private boolean doDBModify(String username, String password) {
		Transaction tx = null;
		boolean result = false;
		try {
			tx = userDao.beginTransaction();
			User user = (User) userDao.findByUsername(username).get(0);
			user.setPassword(password);
			userDao.save(user);
			tx.commit();
			result = true;
		} catch (HibernateException e) {
			if (tx != null) {
				tx.rollback();
				e.printStackTrace();
			}
		} finally {
			userDao.closeSession();
		}
		return result;
	}

	public LoginService getLoginService() {
		return loginService;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}
